<template>
    <a-modal
        :visible="visible"
        title="分组管理"
        :width="600"
        :mask-closable="false"
        @cancel="handleCancel"
    >
        <div class="manage-groups-content">
            <div class="header">
                <a-button type="primary" icon="plus" @click="handleAdd">添加分组</a-button>
            </div>
            <a-table
                :columns="columns"
                :data-source="localGroups"
                :pagination="false"
                row-key="key"
                size="middle"
                bordered
            >
                <template #name="text, record">
                    <div v-if="editingKey === record.key">
                        <a-input v-model="editingName" style="width: 120px; margin-right: 8px;" @pressEnter="saveEdit(record.key)" />
                    </div>
                    <div v-else>
                        {{ text }}
                        <a-tag v-if="isDefaultGroup(record)" color="blue" style="margin-left: 8px;">默认</a-tag>
                    </div>
                </template>

                <template #actions="text, record">
                    <div class="actions">
                        <template v-if="editingKey === record.key">
                            <a @click="saveEdit(record.key)">保存</a>
                            <a-divider type="vertical" />
                            <a @click="cancelEdit">取消</a>
                        </template>
                        <template v-else>
                            <!-- 默认分组不显示编辑和删除按钮 -->
                            <template v-if="!isDefaultGroup(record)">
                                <a @click="startEdit(record)">编辑</a>
                                <a-divider type="vertical" />
                                <a-popconfirm
                                    title="确定删除吗？"
                                    ok-text="确定"
                                    cancel-text="取消"
                                    @confirm="() => handleDelete(record.key)"
                                >
                                    <a class="danger">删除</a>
                                </a-popconfirm>
                            </template>
                            <template v-else>
                                <span style="color: #999;">默认分组不可操作</span>
                            </template>
                        </template>
                    </div>
                </template>
            </a-table>
        </div>
        
        <!-- 添加分组对话框 -->
        <a-modal
            :visible="addModalVisible"
            title="添加分组"
            :width="400"
            @ok="handleAddOk"
            @cancel="handleAddCancel"
        >
            <a-form :form="addForm" layout="vertical">
                <a-form-item label="分组名称">
                    <a-input
                        v-decorator="['groupName', { rules: [{ required: true, message: '请输入分组名称' }] }]"
                        placeholder="请输入分组名称"
                        @pressEnter="handleAddOk"
                    />
                </a-form-item>
            </a-form>
        </a-modal>
        
        <template #footer>
            <a-button @click="handleCancel">关闭</a-button>
        </template>
    </a-modal>
</template>

<script>
export default {
    name: 'ManageGroupsModal',
    props: {
        visible: { type: Boolean, required: true },
        groups: { type: Array, required: true } // groups should be: [{ key, title }]
    },
    data() {
        return {
            localGroups: [],
            editingKey: '',
            editingName: '',
            addModalVisible: false,
            addForm: this.$form.createForm(this),
            columns: [
                { title: '分组名称', dataIndex: 'title', width: '60%', scopedSlots: { customRender: 'name' } },
                { title: '操作', dataIndex: 'actions', scopedSlots: { customRender: 'actions' } }
            ]
        }
    },
    watch: {
        visible(val) {
            if (val) {
                // Deep copy to avoid mutating prop directly
                this.localGroups = JSON.parse(JSON.stringify(this.groups))
                console.log('🔍 [ManageGroupsModal] 分组数据:', this.groups)
                console.log('🔍 [ManageGroupsModal] 本地分组数据:', this.localGroups)
                this.cancelEdit()
            }
        }
    },
    methods: {
        isDefaultGroup(record) {
            // 通过分组名称判断是否为默认分组
            const title = record.title || record.name || ''
            const isDefault = title === '默认分组'
            
            console.log('🔍 [ManageGroupsModal] 检查默认分组:', { 
                key: record.key, 
                title: title, 
                isDefault: isDefault 
            })
            
            return isDefault
        },
        handleCancel() {
            this.$emit('update:visible', false)
        },
        handleAdd() {
            this.addModalVisible = true
            this.$nextTick(() => {
                this.addForm.resetFields()
            })
        },
        handleAddOk() {
            this.addForm.validateFields((err, values) => {
                if (!err) {
                    const newGroup = {
                        key: `group-${Date.now()}`,
                        title: values.groupName
                    }
                    this.localGroups.push(newGroup)
                    this.$emit('add', newGroup)
                    // 只关闭添加分组对话框，不关闭分组管理弹框
                    this.addModalVisible = false
                    // 可以显示成功提示
                    this.$message.success('分组添加成功')
                }
            })
        },
        handleAddCancel() {
            this.addModalVisible = false
        },
        startEdit(record) {
            this.editingKey = record.key
            this.editingName = record.title
        },
        cancelEdit() {
            this.editingKey = ''
            this.editingName = ''
        },
        saveEdit(key) {
            const group = this.localGroups.find(g => g.key === key)
            if (group && this.editingName) {
                group.title = this.editingName
                this.$emit('edit', { key, title: this.editingName })
                this.cancelEdit()
            }
        },
        handleDelete(key) {
            this.localGroups = this.localGroups.filter(g => g.key !== key)
            this.$emit('delete', key)
        }
    }
}
</script>

<style scoped>
.manage-groups-content .header {
    margin-bottom: 16px;
}
.actions a {
    margin-right: 8px;
}
.actions a.danger {
    color: #ff4d4f;
}
</style> 